/**
 */

package com.huisou.search;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.solr.common.params.MultiMapSolrParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @version $Id$
 */
public class SearchSolrParams extends MultiMapSolrParams {
	
	private static final long	serialVersionUID	= 1L;
	
	private static Logger		log					= LoggerFactory.getLogger(SearchSolrParams.class);
	
	public SearchSolrParams(Map<String, String[]> map) {
		super(map);
	}
	
	public static Map<String, String[]> convertParams(HttpServletRequest req) throws Exception {
		log.debug("===== =====>开始处理参数");
		// 获取扩展参数
		String uri = req.getRequestURI();
		Map<String, String[]> map = new HashMap<String, String[]>();
		if (uri.lastIndexOf(".html") > 0) {
			int s = uri.lastIndexOf("/");
			int e = uri.lastIndexOf(".html");
			String param = uri.substring(s + 1, e);
			String[] ps = param.split("_");
			if (ps != null && ps.length > 0) {
				String lprice = "";
				String hprice = "";
				List<String> ls = new ArrayList<String>();
				for (String str : ps) {
					String[] ks = str.split("-");
					if (ks != null && ks.length == 2) {
						if ("k".equals(ks[0])) // 查询关键词
						{
							String q = URLDecoder.decode(ks[1], "UTF-8");
							q = q.replaceAll("=2D", "-");
							map.put("q", new String[] { q });
						}
						else if ("g".equals(ks[0])) {
							if (uri.contains("sale")) {
								map.put("group", new String[] { "true" });
								map.put("group.field", new String[] { "eid" });
								map.put("group.ngroups", new String[] { "true" });
								map.put("g", new String[] { "1" });
							}
						}
						else if ("p".equals(ks[0])) // 类别ID
						{
							ls.add("cateCode:" + ks[1] + "*");
							map.put("pid", new String[] { ks[1] });
						}
						else if ("c".equals(ks[0])) // 城市ID
						{
							ls.add("cityId:" + ks[1]);
							map.put("cid", new String[] { ks[1] });
						}
						else if ("s".equals(ks[0])) // 省份ID
						{
							ls.add("stateId:" + ks[1]);
							map.put("sid", new String[] { ks[1] });
						}
						else if ("t".equals(ks[0])) // 产品或资讯发布时间
						{
							ls.add(" begindate:[NOW-" + ks[1].trim() + "DAY TO *]");
							map.put("tme", new String[] { ks[1] });
						}
						else if ("l".equals(ks[0])) // 产品最低价
						{
							lprice = ks[1];
							map.put("lprice", new String[] { lprice });
						}
						else if ("d".equals(ks[0])) // 公司Id
						{
							ls.add("eid:" + ks[1]);
						}
						else if ("h".equals(ks[0])) // 产品最低价
						{
							hprice = ks[1];
							map.put("hprice", new String[] { hprice });
						}
						else if ("m".equals(ks[0])) // 公司经营方式
						{
							ls.add("opmodeId:" + ks[1]);
							map.put("ome", new String[] { ks[1] });
						}
						else if ("e".equals(ks[0])) // 公司成立时间
						{
							Integer n = Integer.parseInt(ks[1]);
							Calendar now = Calendar.getInstance();
							int cy = now.get(Calendar.YEAR);
							int sy = cy - n + 1;
							ls.add("setupdate:[* TO " + sy + "]");
							map.put("sde", new String[] { ks[1] });
						}
						else if ("b".equals(ks[0])) // 起始记录数
						{
							map.put("start", new String[] { ks[1] });
						}
						else if ("o".equals(ks[0]) && (!"0".equals(ks[1]))) // 排序方式
						{
							String or = ks[1];
							map.put("srt", new String[] { or });
							if ("1".equals(or)) {
								map.put("sort", new String[] { " pirce asc " }); // 价格从低到高
							}
							else if ("2".equals(or)) {
								map.put("sort", new String[] { " pirce desc " }); // 价格从高到低
							}
							else if ("3".equals(or)) // 活跃企业
							{
								map.put("sort", new String[] { " totalPoint desc " }); // 指数从高到低
							}
							else if ("4".equals(or)) {
								map.put("sort", new String[] { " begindate asc " }); // 越早发布的越靠前
							}
							else if ("5".equals(or)) {
								map.put("sort", new String[] { " views desc " }); // 浏览数从高到低
							}
							else if ("6".equals(or)) // 最新加盟企业
							{
								map.put("sort", new String[] { "  lastmodify desc " }); // 按加入的先后顺序排
							}
						}
						else if ("n".equals(ks[0])) // 频道
						{
							String chn = ks[1];
							map.put("chn", new String[] { chn });
							if ("s".equals(chn)) {
								ls.add("typeId:1 AND kindId:72");
							}
							else if ("u".equals(chn)) {
								ls.add("typeId:2 AND kindId:72 ");
							}
							else if ("e".equals(chn)) {
								ls.add("typeId:1 AND kindId:[73 TO 76]");
							}
						}
						else if ("w".equals(ks[0])) // 显示方式--win : 大图 - lst : 列表
						{
							map.put("win", new String[] { ks[1] });
						}
						else if ("i".equals(ks[0])) // 行业Code
						{
							ls.add("profCode:" + ks[1] + "*");
							map.put("iid", new String[] { ks[1] });
						}
						else if ("u".equals(ks[0])) // 状态
						{
							ls.add("statusFlg:" + ks[1]);
							map.put("sta", new String[] { ks[1] });
						}
						else if ("a".equals(ks[0])) {
							map.put("sort", new String[] { " " }); // 按时间排序
						}
						else if ("v".equals(ks[0])) // 认证企业
						{
							ls.add("isVip:" + ks[1]);
							map.put("vip", new String[] { ks[1] });
						}
						else if ("x".equals(ks[0])) // 是否为混批
						{
							ls.add("tomix:" + ks[1]);
							map.put("tomix", new String[] { ks[1] });
						}
					}
				}
				if (lprice != "" && hprice != "") {
					ls.add("pirce:[" + lprice + " TO " + hprice + "]");
				}
				else if (lprice != "") {
					ls.add("pirce:[" + lprice + " TO *]");
				}
				else if (hprice != "") {
					ls.add("pirce:[* TO " + hprice + "]");
				}
				
				if (ls.size() > 0) {
					String[] strs = new String[ls.size()];
					for (int i = 0; i < ls.size(); i++) {
						strs[i] = ls.get(i);
					}
					map.put("fq", strs);
				}
				
				if (!map.containsKey("start"))
					map.put("start", new String[] { "0" });
				// if (uri.contains("suggest")) map.put("spellcheck.build", new String[] { "true" });
			}
		}
		else if (uri.indexOf("/newsapi") > -1) {
			String query = req.getQueryString();
			if (StringUtils.isNotBlank(query)) {
				map = newsApiParse(URLDecoder.decode(query.trim(), "UTF-8"));
			}
		}
		else if (uri.indexOf("/api") > -1) {
			String query = req.getQueryString();
			if (null != query && !"".equals(query)) {
				map = parseSale(URLDecoder.decode(query.trim(), "UTF-8"));
			}
		}
		else if (uri.indexOf("/bns") > -1) {
			String query = req.getQueryString();
			if (StringUtils.isNotBlank(query)) {
				map = initBnsParams(URLDecoder.decode(query.trim(), "UTF-8"));
			}
		}
		else if (req.getParameter("q") != null) {
			String str = req.getParameter("q"); // str = URLDecoder.decode(str,"UTF-8");
			str = new String(str.getBytes("UTF-8"), "UTF-8");
			str = new String(str.getBytes("ISO-8859-1"), "UTF-8");
			log.debug("查询参数为：{}", str);
			map.put("q", new String[] { str });
			String b = req.getParameter("b");
			if (b == null)
				b = "0";
			map.put("start", new String[] { b });
		}
		else {
			map = req.getParameterMap();
		}
		return map;
	}
	
	@Override
	public String get(String name) {
		String[] arr = map.get(name);
		if (arr == null)
			return null;
		String s = arr[0];
		if (s.length() == 0)
			return null; // screen out blank parameters
		return s;
	}
	
	private static void addPrefix(StringBuilder q) {
		if (q != null && q.length() > 0)
			q.append(" AND ");
	}
	
	public static Map<String, String[]> newsApiParse(String query) {
		Map<String, String[]> map = new HashMap<String, String[]>();
		if (StringUtils.isNotBlank(query)) {
			List<String> fq = new ArrayList<String>();
			for (String temp : query.split("&")) {
				String kv[] = temp.split("=");
				if (kv.length == 2) {
					String key = kv[0];
					String val = kv[1];
					if ("p".equals(key)) {
						val = "cateCode:" + val + "*";
						fq.add(val);
					}
					else if ("i".equals(key)) {
						val = "profCode:" + val + "*";
						fq.add(val);
					}
					else if ("pic".equals(key) && "on".equals(val)) {
						fq.add("micropic:['' TO *]");
					}
					else if ("part".equals(key)) {
						val = "part:" + val;
						fq.add(val);
					}
					map.put(key, new String[] { val });
				}
				else {
					String key = kv[0];
					map.put(key, new String[] { "" });
				}
				
				if (fq.size() > 0) {
					String[] strs = new String[fq.size()];
					for (int i = 0; i < fq.size(); i++) {
						strs[i] = fq.get(i);
					}
					map.put("fq", strs);
				}
			}
		}
		return map;
	}
	
	private static Map<String, String[]> initBnsParams(String query) {
		Map<String, String[]> map = new HashMap<String, String[]>();
		if (StringUtils.isNotBlank(query)) {
			List<String> fq = new ArrayList<String>();
			for (String temp : query.split("&")) {
				String kv[] = temp.split("=");
				if (kv.length == 2) {
					String key = kv[0];
					String val = kv[1];
					if ("b".equals(key)) {
						key = "start";
					}
					else if ("e".equals(key)) {
						key = "q";
					}
					else if ("p".equals(key)) {
						fq.add("stateId:" + val);
					}
					else if ("c".equals(key)) {
						fq.add("cityId:" + val);
					}
					else if ("f".equals(key)) {
						fq.add("code:" + val);
					}
					else if ("s".equals(key)) {
						fq.add("cateCode:" + val);
					}
					else if ("fid".equals(key)) {
						fq.add("pid:" + val);
					}
					map.put(key, new String[] { val });
				}
				else {
					String key = kv[0];
					map.put(key, new String[] { "" });
				}
			}
			
			if (fq.size() > 0) {
				String[] strs = new String[fq.size()];
				for (int i = 0; i < fq.size(); i++) {
					strs[i] = fq.get(i);
				}
				map.put("fq", strs);
			}
		}
		return map;
	}
	
	public static Map<String, String[]> parseSale(String str) {
		Map<String, String[]> map = new HashMap<String, String[]>();
		if (!"".equals(str)) {
			List<String> fq = new ArrayList<String>();
			for (String temp : str.split("&")) {
				String kv[] = temp.split("=");
				if (kv.length == 2) {
					String key = kv[0];
					String val = kv[1];
					if ("b".equals(key)) {
						key = "start";
					}
					else if ("p".equals(key)) {
						val = "cateCode:" + val + "*";
						fq.add(val);
					}
					else if ("c".equals(key)) {
						val = "cityId:" + val;
						fq.add(val);
					}
					map.put(key, new String[] { val });
				}
				else {
					String key = kv[0];
					map.put(key, new String[] { "" });
				}
				if (fq.size() > 0) {
					String[] strs = new String[fq.size()];
					for (int i = 0; i < fq.size(); i++) {
						strs[i] = fq.get(i);
					}
					map.put("fq", strs);
				}
			}
		}
		return map;
	}
}
